export default class handsontableHelper {
  constructor(t) {
    this.hotInstance = t,
      this.alignDirectionRegExp = /font-text-align-(left|center|right)/,
      this.indentClsRegExp = /indent-(left|right)-(\d+)/
  }
  getMergeCells() {
    return this.hotInstance.getSettings().mergeCells
  }
  getSelection() {
    var e = this.hotInstance.getSelected()[0];
    return e ? {
      row: e[0],
      col: e[1],
      endRow: e[2],
      endCol: e[3]
    } : null
  }
  rgbToHex(e, t, n) {
    function o(e) {
      var t = e.toString(16);
      return 1 == t.length ? "0" + t : t
    }
    return "#" + o(e) + o(t) + o(n)
  }

  hexToRgb(e) {
    var t = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);
    return t ? [parseInt(t[1], 16), parseInt(t[2], 16), parseInt(t[3], 16)] : null
  }

  genNewCellMeta(e) {
    return {
      row: e.row,
      col: e.col,
      className: e.className
    }
  }

  _defaultSelection(e) {
    return e.row > e.endRow && (e.row = [e.endRow, e.endRow = e.row][0]),
      e.col > e.endCol && (e.col = [e.endCol, e.endCol = e.col][0]),
    {
      startRow: e.row,
      endRow: e.endRow || e.row,
      startCol: e.col,
      endCol: e.endCol || e.col
    }
  }
  select(e, t, n, o) {
    n = n || e,
      o = o || t,
      this.hotInstance.selectCell(e, t, n, o, !1)
  }

  getCellClass(e, t) {
    if (!e || !e.className)
      return null;
    if (!t)
      return e.className;
    var n = e.className.match(t);
    return n && n.length > 1 ? {
      className: n[0],
      classParam: n.slice(1)
    } : void 0
  }

  getOriginalTextAlign(e) {
    var t = this.getCellClass(e, this.alignDirectionRegExp);
    if (t && 1 === t.classParam.length)
      return t.classParam[0]
  }

  getOriginalIndent(e) {
    var t = this.getCellClass(e, this.indentClsRegExp);
    if (!t)
      return {
        indentDirection: null,
        indentTimes: null
      };
    var n = F(t.classParam, 2)
      , o = n[0]
      , r = n[1];
    return {
      indentDirection: o,
      indentTimes: Number.parseInt(r)
    }
  }

  replaceClassName(e, t, n) {
    return this.organizeClassName(e.replace(n, "").trim() + " " + t)
  }

  replaceClass(e, t, n) {
    return e && e.className ? this.replaceClassName(e.className, t, n) : null
  }

  hasClass(e, t) {
    if (!t || !e)
      return !1;
    var n = e.className;
    return !!n && new RegExp(t).test(n)
  }

  addClass(e, t) {
    if (!e)
      return null;
    if (!e.className)
      return t;
    var n = e.className;
    return this.addClassName(n, t)
  }

  addClassName(e, t) {
    return new RegExp(t).test(e) ? e : e ? e + " " + t : t
  }

  removeClass(e, t) {
    return e && e.className ? this.organizeClassName(e.className.replace(t, "")) : null
  }

  organizeClass(e) {
    return e && e.className ? this.organizeClassName(e.className) : null
  }

  organizeClassName(e) {
    return e.split(" ").reduce(function (e, t) {
      return t ? e ? e + " " + t : t : e
    })
  }

  getSingleBorderClassName(e, t, n, o) {
    var r = ""
      , i = ""
      , a = "";
    return "none" !== t && (r = " border-" + e + "-style-" + t + " ",
      i = " border-" + e + "-color-" + o + " ",
      a = " border-" + e + "-width-" + n + " "),
      r + " " + i + " " + a + " "
  }

  calculateCellsBorder(e, t, n, o) {
    var r = this
      , i = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : this.getSelection();
    if (!i)
      return null;
    i = this._defaultSelection(i);
    var a = new RegExp("border-(top|right|bottom|left)-(style|color|width)-[^\\s]+", "gi")
      , s = {
        width: t = t || 1,
        style: n,
        color: o
      }
      , l = function (e, t, n) {
        return ["top", "right", "bottom", "left"].map(function (o, i) {
          return r.getSingleBorderClassName(o, e[i], t, n)
        }).join(" ")
      }
      , u = function (startRow, endRow, startCol, borderStyle) {
        // 遍历行 将每行起始列的前一列单元格添加right边框
        for (var c = [], sr = startRow; sr <= endRow; sr++) {
          if (startCol > 0) {
            var h = r.hotInstance.getCellMeta(sr, startCol - 1)
              , f = r.replaceClassName(h.className || "", r.getSingleBorderClassName("right", n, t, o), new RegExp("border-right-(style|color|width)-[^\\s]+", "gi"));
            c.push({
              row: sr,
              col: startCol - 1,
              className: f
            });
            var p = r.hotInstance.getCellMeta(sr, startCol);
            c.push({
              row: sr,
              col: startCol,
              border: borderStyle || Object.assign({}, p.border || {}, {
                right: Object.assign({}, s)
              })
            })
          } else {
            //起始列为第一行
            var h = r.hotInstance.getCellMeta(sr, startCol), f = ''
            if ('left' === e) {
              f = r.replaceClassName(h.className || "", l(["none", "none", "none", n], t, o), new RegExp("border-left-(style|color|width)-[^\\s]+", "gi"));
            } else {
              //设置所有框线、外侧框线
              if (sr === 0) {
                //（0，0）单元格 设置所有边框
                f = r.replaceClassName(h.className || "", l([n, n, n, n], t, o), a);
              } else {
                //（r，0）单元格 设置left right bottom 
                f = r.replaceClassName(h.className || "", l(['none', n, n, n], t, o), new RegExp("border-(left|right|bottom)-(style|color|width)-[^\\s]+", "gi"));
              }
            }
            console.log(f, 'uuuuu');
            c.push({
              row: sr,
              col: startCol,
              className: f
            });
          }
        }

        return c
      }
      //startCol,endCol,startRow,borderStyle
      , c = function (startCol, endCol, startRow, borderStyle) {
        // 遍历列 将每列起始行的前一行单元格添加bottom边框
        for (var c = [], sc = startCol; sc <= endCol; sc++) {
          if (startRow > 0) {
            var h = r.hotInstance.getCellMeta(startRow - 1, sc)
              , f = r.replaceClassName(h.className || "", r.getSingleBorderClassName("bottom", n, t, o), new RegExp("border-bottom-(style|color|width)-[^\\s]+", "gi"));
            c.push({
              row: startRow - 1,
              col: sc,
              className: f
            });
            var p = r.hotInstance.getCellMeta(startRow, sc);
            c.push({
              row: startRow,
              col: sc,
              border: borderStyle || Object.assign({}, p.border || {}, {
                bottom: Object.assign({}, s)
              })
            })
          } else {
            //起始行为第一行
            var h = r.hotInstance.getCellMeta(startRow, sc),
              f = ''
            if ('top' === e) {
              f = r.replaceClassName(h.className || "", l([n, 'none', 'none', 'none'], t, o), new RegExp("border-top-(style|color|width)-[^\\s]+", "gi"));
            } else {
              //设置所有框线、外侧框线
              if (sc === 0) {
                //（0，0）单元格 设置所有边框
                f = r.replaceClassName(h.className || "", l([n, n, n, n], t, o), a);
              } else {
                //（0，c）单元格 设置top right bottom
                f = r.replaceClassName(h.className || "", l([n, n, n, 'none'], t, o), new RegExp("border-(top|right|bottom)-(style|color|width)-[^\\s]+", "gi"));
              }
            }
            console.log(f, 'ccc');
            c.push({
              row: startRow,
              col: sc,
              className: f
            });
          }
        }

        return c
      }
      , d = i
      , h = d.startRow
      , f = d.endRow
      , p = d.startCol
      , m = d.endCol
      , g = [];
    if ("all" === e) {
      for (var y = {
        top: Object.assign({}, s),
        right: Object.assign({}, s),
        bottom: Object.assign({}, s),
        left: Object.assign({}, s)
      }, v = "none" != n ? y : {}, w = h; w <= f; w++)
        for (var _ = p; _ <= m; _++) {
          var b, C = this.hotInstance.getCellMeta(w, _);
          //当前单元格设置右和下边框
          b = this.replaceClassName(C.className || "", l(['none', n, n, 'none'], t, o), a),
            g.push({
              row: w,
              col: _,
              className: b,
              border: v
            })
        }
      //设置选中区域 起始行上边框 起始列左边框
      var T = c(p, m, h, v)
        , M = u(h, f, p, v);
      return "none" === n && (g = g.concat(function (e, t, n, o) {
        for (var i = r.hotInstance.countCols(), a = r.hotInstance.countRows(), s = [], l = function (e, t, n) {
          var o = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}
            , r = Object.assign({}, o);
          return delete r[e],
          {
            row: t,
            col: n,
            border: r
          }
        }, u = e; u <= n; u++) {
          if (t >= 1) {
            var c = r.hotInstance.getCellMeta(u, t - 1);
            c.border && s.push(l("right", u, t - 1, c.border))
          }
          if (o + 1 <= i) {
            var d = r.hotInstance.getCellMeta(u, o + 1);
            d.border && s.push(l("left", u, o + 1, d.border))
          }
        }
        for (var h = t; h <= o; h++) {
          if (e >= 1) {
            var f = r.hotInstance.getCellMeta(e - 1, h);
            f.border && s.push(l("bottom", e - 1, h, f.border))
          }
          if (n + 1 <= a) {
            var p = r.hotInstance.getCellMeta(n + 1, h);
            p.border && s.push(l("top", n + 1, h, p.border))
          }
        }
        return s
      }(h, p, f, m))),
        g.concat(T).concat(M)
    }
    if ("outside" === e) {
      for (var S = c(p, m, h), k = u(h, f, p), E = Object.create({}), O = h; O <= f; O++)
        for (var L = p; L <= m; L++)
          E[O + ":" + L] || (E[O + ":" + L] = {},
            E[O + ":" + L].border = []),
            O === h && E[O + ":" + L].border.push("top"),
            O === f && E[O + ":" + L].border.push("bottom"),
            L === p && E[O + ":" + L].border.push("left"),
            L === m && E[O + ":" + L].border.push("right");
      var D = function (e) {
        var i = e.split(":")
          , a = i[0]
          , l = i[1]
          , u = r.hotInstance.getCellMeta(a, l)
          , c = E[e].border.filter(function (e) {
            if (a == 0) {
              if (l == 0) {
                return true
              } else {
                return "left" !== e
              }
            } else if (l == 0) {
              if (a == 0) {
                return true
              } else {
                return "top" !== e
              }
            } else {
              return "left" !== e && "top" !== e
            }
          })
          , d = {};
        E[e].border.forEach(function (e) {
          d[e] = Object.assign({}, s)
        });
        var h = Object.assign({}, u.border || {}, d);
        g.push({
          row: a,
          col: l,
          className: r.replaceClassName(u.className || "", c.map(function (e) {
            return r.getSingleBorderClassName(e, n, t, o)
          }).join(" "), new RegExp("border-(" + c.join("|") + ")-(style|color|width)-[^\\s]+", "gi")),
          border: h
        })
      };
      for (var x in E)
        D(x);
      return S.concat(k).concat(g)
    }
    return "right" === e ? g.concat(function (e, i, a) {
      for (var l = [], u = e; u <= i; u++) {
        var c = r.hotInstance.getCellMeta(u, a)
          , d = r.replaceClassName(c.className || "", r.getSingleBorderClassName("right", n, t, o), new RegExp("border-right-(style|color|width)-[^\\s]+", "gi"));
        l.push({
          row: u,
          col: a,
          className: d,
          border: Object.assign({}, c.border || {}, {
            right: Object.assign({}, s)
          })
        })
      }
      return l
    }(h, f, m)) : "bottom" === e ? g.concat(function (e, i, a) {
      for (var l = [], u = e; u <= i; u++) {
        var c = r.hotInstance.getCellMeta(a, u)
          , d = r.replaceClassName(c.className || "", r.getSingleBorderClassName("bottom", n, t, o), new RegExp("border-bottom-(style|color|width)-[^\\s]+", "gi"));
        l.push({
          row: a,
          col: u,
          className: d,
          border: Object.assign({}, c.border || {}, {
            bottom: Object.assign({}, s)
          })
        })
      }
      return l
    }(p, m, f)) : "left" === e ? u(h, f, p) : "top" === e ? c(p, m, h) : void 0
  }

  genCellsNewStyles(e, t, n) {
    var o = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : this.getSelection();
    if (!o)
      return null;
    for (var r = o = this._defaultSelection(o), i = r.startRow, a = r.endRow, s = r.startCol, l = r.endCol, u = [], c = i; c <= a; ++c)
      for (var d = s; d <= l; ++d) {
        var h = ""
          , f = {}
          , p = this.hotInstance.getCellMeta(c, d)
          , m = {
            row: c,
            col: d
          };
        h = p && p.className ? t ? this.replaceClassName(p.className, e, t) : p.className : e,
          m.className = h,
          n && ((f = Object.assign({}, p.style || {}, n)).color && "#00000000" === f.color && delete f.color,
            f.backgroundColor && "#00000000" === f.backgroundColor && delete f.backgroundColor,
            m.style = f),
          u.push(m)
      }
    return u
  }

  formatPainterCopy() {
    var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.getSelection();
    if (!e)
      return null;
    e = this._defaultSelection(e),
      this.hotInstance.rootElement.classList.add("formatPainter"),
      this.hotInstance.copyedFormat = e
  }

  getContainedMergeCells(e) {
    if (!e)
      return null;
    var t = this.getMergeCells();
    return t && Array.isArray(t) ? t.filter(function (t) {
      return t.row >= e.startRow && t.row <= e.endRow && t.col >= e.startCol && t.col <= e.endCol
    }).slice() : null
  }

  getCellMetaFromCopyRange(e, t) {
    return this.hotInstance.copyedRange && this.hotInstance.copyedRange.cellMetas ? this.hotInstance.copyedRange.cellMetas[e][t] : null
  }

  getSelectedCellMeta(e) {
    var t = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.getSelection();
    if (!t)
      return null;
    for (var n = this._defaultSelection(t), o = n.startRow, r = n.endRow, i = n.startCol, a = n.endCol, s = [], l = o; l <= r; ++l)
      for (var u = i; u <= a; ++u) {
        var c = this.hotInstance.getCellMeta(l, u);
        c || e ? s.push(c) : s.push({
          row: l,
          col: u
        })
      }
    return s
  }

  forEachSelectedCellMeta(e) {
    var t = arguments.length > 1 && arguments[1] !== undefined && arguments[1]
      , n = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.getSelection();
    if (!n)
      return null;
    for (var o = this._defaultSelection(n), r = o.startRow, i = o.endRow, a = o.startCol, s = o.endCol, l = r; l <= i; ++l)
      for (var u = a; u <= s; ++u) {
        var c = this.hotInstance.getCellMeta(l, u);
        e(c || t ? c : {
          row: l,
          col: u
        })
      }
  }

  forEachSelectedRowCellMeta(e, t) {
    var n = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.getSelection();
    if (!n)
      return null;
    for (var o = n.row, r = this.hotInstance.countCols(), i = 0; i < r; i++) {
      var a = this.hotInstance.getCellMeta(o, i);
      e(a || t ? a : {
        row: o,
        col: i
      })
    }
  }

  forEachRowCellMeta(e, t) {
    if (!(arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.getSelection()))
      return null;
    for (var n = this.hotInstance.countRows(), o = 0; o < n; o++) {
      var r = this.hotInstance.getCellMeta(o, 0);
      e(r || t ? r : {
        row: o,
        col: 0
      })
    }
  }

  forSingleSelectedCell(e, t) {
    var n = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.getSelection();
    if (!n)
      return null;
    var o = n.row
      , r = n.col
      , i = this.hotInstance.getCellMeta(o, r);
    e(i || t ? i : {
      row: o,
      col: r
    })
  }

  getCellMeta(e, t, n) {
    return n ? this.getCellMetaFromCopyRange(e, t) : this.hotInstance.getCellMeta(e, t)
  }

  cellsStyleClone(e, t, n, o, r) {
    var i = null
      , a = null;
    n ? i = a = 0 : (i = e.startRow,
      a = e.startCol);
    for (var s = t.height, l = t.width, u = t.originPonit, c = [], d = [], h = 0; h <= s; h++)
      for (var f = 0; f <= l; f++) {
        var p = this.getCellMeta(h + i, f + a, n)
          , m = (p && p.border,
            p.className || "")
          , g = {
            row: h + u.row,
            col: f + u.col,
            className: m,
            style: Object.assign({}, JSON.parse(JSON.stringify(p.style || {}))),
            border: Object.assign({}, JSON.parse(JSON.stringify(p.border || {})))
          };
        c.push(g)
      }
    var y = {
      startRow: i,
      endRow: i + s,
      startCol: a,
      endCol: a + l
    }
      , v = this.getContainedMergeCells(y);
    v && (d = v.map(function (e) {
      return {
        row: e.row - y.startRow + u.row,
        col: e.col - y.startCol + u.col,
        rowspan: Math.min(e.rowspan, Math.abs(s + 1 - (e.row - y.startRow))),
        colspan: Math.min(e.colspan, Math.abs(l + 1 - (e.col - y.startCol)))
      }
    }));
    var w = c.concat([]);
    return [{
      clonedCells: w,
      mergedCells: d
    }]
  }

  formatPainterPaste(e, t, n) {
    var o = [];
    if (!e)
      return o;
    var r = t ? {
      startRow: 0,
      startCol: 0,
      endRow: this.hotInstance.copyedRange && this.hotInstance.copyedRange.cellMetas && this.hotInstance.copyedRange.cellMetas.length - 1,
      endCol: this.hotInstance.copyedRange && this.hotInstance.copyedRange.cellMetas && this.hotInstance.copyedRange.cellMetas[0].length - 1
    } : this.hotInstance.copyedFormat
      , i = e.startRow
      , a = e.startCol
      , s = e.endRow
      , l = e.endCol
      , u = r.startRow
      , c = r.startCol
      , d = r.endRow
      , h = r.endCol;
    if (i === s && a === l && !n) {
      var f = {
        height: d - u,
        width: h - c,
        originPonit: {
          row: i,
          col: a
        }
      };
      return this.cellsStyleClone(r, f, t, !1, !1)
    }
    var p, m = null, g = null, y = s - i, v = l - a, w = d - u, _ = h - c;
    p = {
      height: Math.min(y, w),
      width: Math.min(v, _),
      originPonit: {
        row: e.startRow,
        col: e.startCol
      }
    },
      y > w && (m = {
        startRow: e.startRow + p.height + 1,
        startCol: e.startCol,
        endRow: e.endRow,
        endCol: e.startCol + p.width
      }),
      v > _ && (g = {
        startRow: e.startRow,
        startCol: e.startCol + p.width + 1,
        endRow: e.endRow,
        endCol: e.endCol
      });
    var b = this.cellsStyleClone(r, p, t, !!m, !!g);
    return o = o.concat(b),
      m || g ? o.concat(this.formatPainterPaste(m, t, !0).concat(this.formatPainterPaste(g, t, !0))) : o
  }

  isMergeCell(e) {
    var t = this.getMergeCells();
    if (t && Array.isArray(t))
      return t.find(function (t) {
        return t.row === e.startRow && t.rowspan === e.endRow - e.startRow + 1 && t.col === e.startCol && t.colspan === e.endCol - e.startCol + 1
      })
  }

  getCellWithField(e, t) {
    var n = this.hotInstance.getSettings();
    return (n && n.cellWithField)[e + ":" + t]
  }
  getCellWithQRcode(e, t) {
    var n = this.hotInstance.getSettings();
    return (n && n.cellWithQRcode)[e + ":" + t]
  }
  getCellWithBRcode(e, t) {
    var n = this.hotInstance.getSettings();
    return (n && n.cellWithBRcode)[e + ":" + t]
  }
  getCellWithImg(e, t) {
    var n = this.hotInstance.getSettings();
    return (n && n.cellWithImg)[e + ":" + t]
  }
  getCustomFieldList() {
    var n = this.hotInstance.getSettings();
    return n && n.customFieldList
  }
  // 获取单元格变量信息
  getCellExpression(e, t) {
    var n = this.getCellWithField(e, t);
    if (!n)
      return null;
    var o = n.Expression;
    if (o) {
      var r = this.hotInstance.getSettings()
        , i = (r && r.expressions).find(function (e) {
          return e.Expression === o
        }) || null;
      return i && (i.RootMetaDataID = n.RootMetaDataID,
        i.FormatConfig = n.FormatConfig,
        i.ApprovalFormatStyle = n.ApprovalFormatStyle),
        i
    }
    return null
  }

  getCellExpressionByExpression(e) {
    if (e) {
      var t = this.hotInstance.getSettings();
      return (t && t.expressions).find(function (t) {
        return t.Expression === e
      }) || null
    }
    return null
  }

  judgeSignatureParam(e, t) {
    var n = this.getCellWithImg(e, t)
      , o = this.getCellWithField(e, t);
    return n && n.IsDigSign || o && o.IsDigSign
  }
}